﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Spanner
{
    internal class Attrs
    {
        internal AList<string, AttrExpr> AttrAList;

        internal void WriteHtml(Context ctxt)
        {
            var seen = new HashSet<string>{};

            for (var attrs = AttrAList; attrs != null; attrs = attrs.Tail) {

                var key = attrs.Key;

                if (seen.Contains(key)) continue;

                seen.Add(key);

                var separator = (string) null;
                ListAttrs.TryGetValue(key, out separator);

                ctxt.Write(" ");
                ctxt.Write(key);
                ctxt.Write("=");
                ctxt.Write("'");
                if (separator == null)
                {
                    attrs.Value.Write(ctxt, JSorHtml.Html);
                }
                else
                {
                    var pastFirst = false;
                    foreach (var x in AList<string, AttrExpr>.LookupAll(attrs, key))
                    {
                        if (pastFirst) ctxt.Write(separator);
                        x.Write(ctxt, JSorHtml.Html);
                        pastFirst = true;
                    }
                }
                ctxt.Write("'");

            }
        }

        internal Attrs WithAttr(string key, AttrExpr value)
        {
            return new Attrs { AttrAList = AList<string, AttrExpr>.Cons(key, value, AttrAList) };
        }

        /// <summary>
        /// Some attributes can take a list of values.  They are specified here, with the corresponding
        /// separator.
        /// </summary>
        internal static readonly Dictionary<string, string> ListAttrs = new Dictionary<string, string>
        {
            { "style", "; " },
            { "class", " " },
            { "data-bind", ", " }
        };
    }
}
